package com.xuanzheng.company.dao.impl;

import com.xuanzheng.company.dao.AIModelDao;
import com.xuanzheng.company.entity.AIModel;
import com.xuanzheng.company.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * AI模型数据访问实现类
 */
public class AIModelDaoImpl implements AIModelDao {
    
    @Override
    public List<AIModel> findAll() {
        List<AIModel> models = new ArrayList<>();
        String sql = "SELECT * FROM ai_model ORDER BY create_time DESC";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            
            while (rs.next()) {
                models.add(mapResultSetToModel(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return models;
    }
    
    @Override
    public AIModel findById(String id) {
        String sql = "SELECT * FROM ai_model WHERE id = ?";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, id);
            ResultSet rs = pstmt.executeQuery();
            
            if (rs.next()) {
                return mapResultSetToModel(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return null;
    }
    
    @Override
    public AIModel findDefaultModel() {
        // 首先从系统设置中获取默认模型ID
        String sql = "SELECT am.* FROM ai_model am " +
                    "INNER JOIN ai_system_setting ass ON am.id = ass.setting_value " +
                    "WHERE ass.setting_key = 'default_model_id' AND am.status = 1";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            
            if (rs.next()) {
                return mapResultSetToModel(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        // 如果没有设置默认模型，返回第一个启用的模型
        return findFirstEnabledModel();
    }
    
    private AIModel findFirstEnabledModel() {
        String sql = "SELECT * FROM ai_model WHERE status = 1 ORDER BY create_time ASC LIMIT 1";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            
            if (rs.next()) {
                return mapResultSetToModel(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return null;
    }
    
    @Override
    public List<AIModel> findEnabledModels() {
        List<AIModel> models = new ArrayList<>();
        String sql = "SELECT * FROM ai_model WHERE status = 1 ORDER BY create_time DESC";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            
            while (rs.next()) {
                models.add(mapResultSetToModel(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return models;
    }
    
    @Override
    public boolean insert(AIModel model) {
        String sql = "INSERT INTO ai_model (id, name, description, api_key, api_url, status, max_tokens, temperature) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, model.getId());
            pstmt.setString(2, model.getName());
            pstmt.setString(3, model.getDescription());
            pstmt.setString(4, model.getApiKey());
            pstmt.setString(5, model.getApiUrl());
            pstmt.setInt(6, model.getStatus());
            pstmt.setInt(7, model.getMaxTokens());
            pstmt.setDouble(8, model.getTemperature());
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return false;
    }
    
    @Override
    public boolean update(AIModel model) {
        String sql = "UPDATE ai_model SET name = ?, description = ?, api_key = ?, api_url = ?, " +
                    "status = ?, max_tokens = ?, temperature = ?, update_time = CURRENT_TIMESTAMP " +
                    "WHERE id = ?";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, model.getName());
            pstmt.setString(2, model.getDescription());
            pstmt.setString(3, model.getApiKey());
            pstmt.setString(4, model.getApiUrl());
            pstmt.setInt(5, model.getStatus());
            pstmt.setInt(6, model.getMaxTokens());
            pstmt.setDouble(7, model.getTemperature());
            pstmt.setString(8, model.getId());
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return false;
    }
    
    @Override
    public boolean delete(String id) {
        String sql = "DELETE FROM ai_model WHERE id = ?";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, id);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return false;
    }
    
    @Override
    public boolean updateStatus(String id, int status) {
        String sql = "UPDATE ai_model SET status = ?, update_time = CURRENT_TIMESTAMP WHERE id = ?";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setInt(1, status);
            pstmt.setString(2, id);
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return false;
    }
    
    /**
     * 将ResultSet映射为AIModel对象
     */
    private AIModel mapResultSetToModel(ResultSet rs) throws SQLException {
        AIModel model = new AIModel();
        model.setId(rs.getString("id"));
        model.setName(rs.getString("name"));
        model.setDescription(rs.getString("description"));
        model.setApiKey(rs.getString("api_key"));
        model.setApiUrl(rs.getString("api_url"));
        model.setStatus(rs.getInt("status"));
        model.setMaxTokens(rs.getInt("max_tokens"));
        model.setTemperature(rs.getDouble("temperature"));
        model.setCreateTime(rs.getTimestamp("create_time"));
        model.setUpdateTime(rs.getTimestamp("update_time"));
        return model;
    }
}